<template>
  <div class="container" ref="mainCon">
    <div class="mainCon" style="padding-bottom: 0">
      <el-row class="toolbar searchInputWidth" style="padding-bottom: 0">
        <el-form :inline="true" :model="filterField" ref="searchConditions">
          <el-col :lg="8" :xl="6">
            <el-form-item label="单位名称" class="row-padding-bottom">
              <el-input
                type="text"
                placeholder="名称或统一社会信用代码"
                v-model="filterField.keyword"
                clearable
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :lg="8" :xl="6">
            <el-form-item label="动态信用等级" class="row-padding-bottom">
              <el-select
                v-model="filterField.gradeLevel"
                filterable
                placeholder="请选择"
                no-data-text="请选择"
                clearable
                :popper-append-to-body="false"
              >
                <el-option
                  v-for="(item, index) in selectLevel"
                  :key="index"
                  :label="item.name"
                  :value="item.gradeLevel"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <template v-if="advanced">
            <el-col :lg="8" :xl="6">
              <el-form-item label="红黑榜" class="row-padding-bottom">
                <el-select
                  v-model="filterField.rdStatus"
                  filterable
                  placeholder="请选择"
                  no-data-text="请选择"
                  clearable
                  :popper-append-to-body="false"
                >
                  <el-option label="红榜" value="1"></el-option>
                  <el-option label="黑榜" value="0"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :lg="8" :xl="6">
              <el-form-item label="是否信用免单" class="row-padding-bottom">
                <el-select
                  v-model="filterField.isFree"
                  filterable
                  placeholder="请选择"
                  no-data-text="请选择"
                  clearable
                  :popper-append-to-body="false"
                >
                  <el-option label="是" value="1"></el-option>
                  <el-option label="否" value="0"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </template>

          <el-col :lg="8" :xl="6">
            <el-form-item label="">
              <a
                @click="toggleAdvanced"
                style="margin-left: 40px; color: #409eff; cursor: pointer"
                class="btnColor"
              >
                {{ advanced ? '收起' : '展开' }}
                <i
                  :class="advanced ? 'el-icon-arrow-up' : 'el-icon-arrow-down'"
                ></i>
              </a>
              <el-button
                type="primary"
                icon="icon iconfont iconchazhao1"
                @click="searchList"
                class="searchBtn"
              >
                <span>搜索</span>
              </el-button>
            </el-form-item>
          </el-col>
        </el-form>
      </el-row>

      <div class="spacing"></div>
      <div
        ref="tableBox"
        :class="hiddleToolBar ? 'tableBoxCur tableBox' : 'tableBoxCur'"
      >
        <div style="margin-bottom: 24px">
          <exportBtn
            :dataLen="tableList.length"
            :filterField="filterField"
            responseType="get"
            api="api-ps/creditCompanyScore/expand/export"
          ></exportBtn>
          <el-button
            class="commonBut saveBtn funComBut outEmployee"
            v-sdc
            @click="setRedBlack('red')"
          >
            <span class="opetareText">设置红榜</span>
          </el-button>
          <el-button
            class="commonBut saveBtn funComBut outEmployee"
            v-sdc
            @click="setRedBlack('black')"
          >
            <span class="opetareText">设置黑榜</span>
          </el-button>
          <el-button
            class="commonBut saveBtn funComBut outEmployee"
            v-sdc
            @click="setRedBlack('isFree')"
          >
            <span class="opetareText">设置信用免单</span>
          </el-button>
          <el-button
            class="commonBut saveBtn funComBut outEmployee"
            v-sdc
            @click="toClear"
          >
            <span class="opetareText">清除标记</span>
          </el-button>
        </div>
        <el-table
          ref="tableBox1"
          :max-height="tableHeight"
          :data="tableList"
          v-loading="loading"
          :header-cell-style="{ background: '#eef1f6', color: '#606266' }"
          highlight-current-row
          stripe
          style="border: 1px solid #dfe6ec"
          @selection-change="handleSelectionChange"
        >
          <el-table-column
            type="selection"
            width="80"
            align="center"
            fixed="left"
          ></el-table-column>
          <el-table-column
            prop="projectName"
            label="单位名称"
            min-width="200"
            fixed="left"
          >
            <template slot-scope="scope">
              <copyText
                :tableIndex="scope.$index"
                :copyTextName="scope.row.companyName"
                :columnName="'companyName'"
              ></copyText>
            </template>
          </el-table-column>
          <el-table-column
            prop="typeDesc"
            label="单位角色"
            align="center"
            :formatter="formatTd"
            min-width="100"
          ></el-table-column>
          <el-table-column
            prop="uscc"
            label="统一社会信用代码"
            align="center"
            :formatter="formatTd"
            min-width="200"
          ></el-table-column>
          <el-table-column
            label="参评项目个数"
            align="center"
            :formatter="formatTd"
            min-width="120"
          >
            <template slot-scope="scope">
              <el-link
                type="primary"
                v-if="scope.row.projectCount"
                @click="toProjectList(scope.row)"
                >{{ scope.row.projectCount }}</el-link
              >
              <span v-else>0</span>
            </template>
          </el-table-column>
          <el-table-column
            prop="score"
            label="月度平均信用分数"
            align="center"
            :formatter="formatTd"
            min-width="160"
            key="1"
          >
            <template slot-scope="scope">
              <span v-if="scope.row.companyAvgScore">
                {{ scope.row.companyAvgScore }}
              </span>
              <span v-else>尚未生成</span>
            </template>
          </el-table-column>
          <el-table-column
            prop="score"
            label="月度平均信用等级"
            align="center"
            :formatter="formatTd"
            min-width="160"
            key="2"
          >
            <template slot-scope="scope">
              <span v-if="scope.row.companyAvgGradeLevel">
                {{ scope.row.companyAvgGradeLevel }}
              </span>
              <span v-else>尚未生成</span>
            </template>
          </el-table-column>
          <el-table-column
            prop="rdStatus"
            label="红黑榜"
            align="center"
            min-width="120"
            fixed="right"
          >
            <template slot-scope="scope">
              <el-button
                size="mini"
                class="smallBtn redBtn"
                v-if="scope.row.rdStatus == '1'"
                >红榜</el-button
              >
              <el-button
                size="mini"
                class="smallBtn blackBtn"
                v-else-if="scope.row.rdStatus == '0'"
                >黑榜</el-button
              >
            </template>
          </el-table-column>
          <el-table-column
            prop="isFree"
            label="信用免单"
            align="center"
            min-width="120"
            fixed="right"
          >
            <template slot-scope="scope">
              <span style="color: #5fab2b" v-if="scope.row.isFree == '1'"
                >信用免单</span
              >
            </template>
          </el-table-column>
          <!-- 表格数据为空时，页面显示 -->
          <div slot="empty" v-show="isShow">
            <emptyTable emptyText="暂无相关数据"></emptyTable>
          </div>
        </el-table>

        <!-- getTableList为获取子组件的数据 -->
        <Pagination
          ref="pagination"
          @getList="getTableList"
          :filterField="filterField"
          :requestUrl="requestUrl"
        ></Pagination>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: 'qyRedBlackSet',
  props: {
    scoreDimType: {
      type: String,
      default: '',
    },
  },
  watch: {
    scoreDimType(newValue, oldValue) {
      this.getLevelList(this.scoreDimType)
      this.filterField.type = newValue
      this.filterField.keyword = ''
      this.filterField.gradeLevel = ''
      this.filterField.rdStatus = ''
      this.filterField.isFree = ''
      this.$nextTick(function () {
        this.$refs.pagination.getTableListData()
      })
    },
  },
  data() {
    return {
      hiddleToolBar: false,
      tableHeight: null,
      advanced: false,
      scoreDimTypeArr: [
        {
          scoreDimType: '0',
          scoreDimTypeDesc: '建设单位',
        },
        {
          scoreDimType: '5',
          scoreDimTypeDesc: '施工单位',
        },
        {
          scoreDimType: '10',
          scoreDimTypeDesc: '分包单位',
        },
      ],
      //表格数据
      tableList: [],
      requestUrl:
        'api-ps/creditCompanyScore/expand/getCompanyScoreListByMonitor',
      //搜索条件
      filterField: {
        type: '0',
        keyword: '',
        gradeLevel: '',
        rdStatus: '',
        isFree: '',
      },
      selectLevel: [],
      isShow: false, //列表加载
      loading: false,
      isShowDetail: '',
      api: '',
      tableDateSelcted: [], //选中的项目
    }
  },
  created() {
    this.getLevelList(this.scoreDimType)
    this.$nextTick(function () {
      this.$refs.pagination.getTableListData()
    })
  },
  methods: {
    toggleAdvanced() {
      this.advanced = !this.advanced
    },
    handleScroll(e) {
      this.$nextTick(function () {
        //变量scrollTop是滚动条滚动时，距离顶部的距离
        var scrollTop = e.target.scrollTop
        if (
          this.$refs.tableBox &&
          this.$refs.tableBox.getBoundingClientRect().top < 128
        ) {
          this.tableHeight = window.innerHeight - 210
          if (document.getElementsByClassName('tableBoxCur').length) {
            document.getElementsByClassName('tableBoxCur')[0].style.height =
              null
          }
          this.hiddleToolBar = true
        } else {
          this.hiddleToolBar = false
        }
      })
    },
    getTableList(data) {
      this.tableList = data
      this.loading = false
      if (this.tableList.length < 1) {
        this.isShow = true
      }
    },
    // 搜索
    searchList() {
      this.$refs.pagination.getTableListData()
    },
    getLevelList(type) {
      return this.axios({
        method: 'post',
        url: 'api-ps/creditLevel/expand/getCreditLevelList',
        data: {
          type,
        },
      })
        .then((response) => {
          if (response.data.hasError) {
            this.$message.error(response.data.errorMsg)
          } else {
            const results = response.data.result
            results.forEach((v) => {
              v.name = v.gradeLevel
            })
            this.selectLevel = results
            const otherLevel = { gradeLevel: 'O', name: '其他' }
            this.selectLevel.push(otherLevel)
          }
        })
        .catch((error) => {
          if (error.response) {
            this.$message.error(error.response.data)
          }
        })
    },
    // 选中的项目
    handleSelectionChange(val) {
      this.tableDateSelcted = val
    },

    // 设置红,黑榜，信用免单
    setRedBlack(type) {
      if (this.tableDateSelcted.length < 1) {
        this.$message.warning('请先选择企业')
        return
      }
      // 设置红榜
      var status = ''
      if (type == 'red') {
        status = '1'
      } else if (type == 'black') {
        // 设置黑榜
        status = '0'
      } else {
        // 设置信用免单  isFree：1
      }
      var addArr = []
      this.tableDateSelcted.forEach((item, i) => {
        let obj = {}
        obj.id = item.rdId
        obj.type = 'COMPANY'
        // obj.projectId = "";
        obj.uscc = item.uscc
        obj.companyType = item.type
        // 信用免单
        if (type === 'isFree') {
          Object.assign(obj, {
            isFree: 1,
            status: item.rdStatus,
          })
        } else {
          Object.assign(obj, {
            status: status,
            isFree: item.isFree,
          })
        }
        addArr.push(obj)
      })

      var data = {
        type: 'COMPANY',
        redBlacks: JSON.stringify(addArr),
      }
      this.axios({
        method: 'post',
        url: 'api-ps/creditredblack/setRedBlack',
        data: data,
      })
        .then((response) => {
          if (response.data.hasError) {
            this.$message.error(response.data.errorMsg)
          } else {
            this.$message.success(response.data.msg || '操作成功')
            this.$nextTick(function () {
              this.$refs.pagination.getTableListData()
            })
          }
        })
        .catch((error) => {
          if (error.response) {
            this.$message.error(error.response.data)
          }
        })
    },
    //清除标记
    toClear() {
      if (this.tableDateSelcted.length < 1) {
        this.$message.warning('请先选择企业')
        return
      }
      var arr = []
      this.tableDateSelcted.forEach((item) => {
        arr.push(item.rdId)
      })
      this.axios({
        method: 'post',
        url: 'api-ps/creditredblack/remove',
        data: {
          ids: JSON.stringify(arr),
        },
      })
        .then((response) => {
          if (response.data.hasError) {
            this.$message.error(response.data.errorMsg)
          } else {
            this.$message.success(response.data.msg || '移除成功')
            this.$nextTick(function () {
              this.$refs.pagination.getTableListData()
            })
          }
        })
        .catch((error) => {
          if (error.response) {
            this.$message.error(error.response.data)
          }
        })
    },
  },
  activated() {
    window.addEventListener('scroll', this.handleScroll, true)
    this.$nextTick(function () {
      this.$refs.tableBox1.doLayout()
    })
  },
  deactivated() {
    let that = this
    window.removeEventListener('scroll', that.handleScroll, true)
  },
  beforeDestroy() {
    let that = this
    window.removeEventListener('scroll', that.handleScroll, true)
  },
  mounted() {
    window.addEventListener('scroll', this.handleScroll, true)
    let that = this
    this.$nextTick(function () {
      let tableHeightCur = this.$refs.tableBox1.$el.clientHeight
      let tableTop = this.$refs.tableBox.getBoundingClientRect().top
      if (tableHeightCur + tableTop > window.innerHeight) {
        this.tableHeight =
          this.$refs.mainCon.getBoundingClientRect().height - 86
      } else {
        document.getElementsByClassName('tableBoxCur').length &&
          (document.getElementsByClassName('tableBoxCur')[0].style.height =
            window.innerHeight - tableTop - 40 + 'px')
      }

      window.onresize = function () {
        if (!that.$refs.tableBox1) {
          return
        }
        let tableHeightCur = that.$refs.tableBox1.$el.clientHeight
        let tableTop = that.$refs.tableBox.getBoundingClientRect().top
        if (tableHeightCur + tableTop > window.innerHeight) {
          that.tableHeight =
            that.$refs.mainCon.getBoundingClientRect().height - 86
        } else {
          document.getElementsByClassName('tableBoxCur').length &&
            (document.getElementsByClassName('tableBoxCur')[0].style.height =
              window.innerHeight - tableTop - 40 + 'px')
        }
      }
    })
  },
}
</script>

<style lang="less" scoped>
.smallBtn {
  color: #fff;
  border: none;
  cursor: default;
}
.redBtn {
  background-color: #d71717;
}

.blackBtn {
  background-color: #000;
}
</style>
